package hxg.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author HeXiangGuang
 * @create 2021-06-23 20:27
 */
public class Demo2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1创建Callable对象
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName()+"开始计算！");
                int sum = 0;
                for (int i = 0; i <100 ; i++) {
                    sum+=i;
                }
                return sum;
            }
        };
        //2.Callble对象转成可执行任务
        FutureTask<Integer> task = new FutureTask<>(callable);
        //3.创建线程
        Thread thread = new Thread(task);
        //4.启动线程
        thread.start();
        //5.获取结果
        Integer sum = task.get();
        System.out.println("1加到100的结果是"+sum);

    }
}
